package com.nariano.server.services.userservice.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.nariano.server.domain.entities.User;
import com.nariano.server.services.userservice.UserService;

public class UserServiceJpa extends JpaDaoSupport implements UserService  {

	private volatile int  nofUser = -1;

	@Transactional(readOnly=true)
    public User findUserFromEmail(String email) {
    	List<User>  list = getJpaTemplate().find("select u3 from User u3 where u3.email='"+email+"'");
        if (list.isEmpty()) { return null; }
        Assert.isTrue(1 == list.size(), "Java datamodel not compliant with db-model: " + list);
        return (User) list.get(0);
    }

	@Transactional(readOnly=true)
    public User findUserFromUserName(String userName) {
        List<User>  list = getJpaTemplate().find("select u2 from User u2 where u2.userName='"+userName+"'");
        if (list.isEmpty()) { return null; }
        Assert.isTrue(1 == list.size(), "Java datamodel not compliant with db-model: " + list.size());
        return (User) list.get(0);
    }

	@Transactional(readOnly=false)
    public void deleteUser(User user) {
    	JpaTemplate ht = getJpaTemplate();
    	User userx = ht.find(User.class, user.getId());
        ht.remove(userx);
        nofUser--;
    }

	@Transactional(readOnly=false)
    public User insertUser(User user) {
        JpaTemplate ht = getJpaTemplate();
        ht.persist(user);
        nofUser++;
        return findUserFromUserName(user.getUserName());
    }

	@Transactional(readOnly=false)
    public void updateUser(User user) {
    	JpaTemplate ht = getJpaTemplate();
        ht.merge(user);
    }
    
	@Transactional(readOnly=true)
    public List<User> getAllUsers() {
        List<User>  list = getJpaTemplate().find("select u1 from User u1");
        return list;
    }
    
    
	@Transactional(readOnly=true)
	public int getNofUsers() {
		if (nofUser == -1) { // huuh
			nofUser = getAllUsers().size();
		}
		
		return nofUser;
	}
	
	@Transactional(readOnly=true)
    public User findUserFromId(Integer id) {
		if (id==null) return null;
		
        List<User>  list = getJpaTemplate().find("select u2 from User u2 where u2.id='"+id+"'");
        if (list.isEmpty()) { return null; }
        Assert.isTrue(1 == list.size(), "Java datamodel not compliant with db-model: " + list.size());
        return (User) list.get(0);
    }

	@Override
	public List<User> findAttackers(Integer id) {
		if (id==null) return new ArrayList<User>();
		List<User>  list = getJpaTemplate().find("select u2 from User u2 where u2.enemyUserId='"+id+"'");
		return list;
	}

	

}
